import React, { useEffect, useMemo, useState } from 'react'
import { Toast, Button, Popup } from 'antd-mobile'
import { NavBar, Field } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import { MoreOutlined, RightOutlined, DownOutlined } from '@ant-design/icons';
// import { RightOutline } from 'antd-mobile-icons'
import { Card, Modal, Form, Input, message } from 'antd';
import './recovery.less'
import { Area } from 'react-vant'
import { areaList } from '@vant/area-data'
import axios from '../../utils/Index'
export default function Recovery() {
    const navigate = useNavigate()
    const [form] = Form.useForm()
    const [visible1, setVisible1] = useState(false)
    const [isModalOpen, setIsModalOpen] = useState(false);  //控制模态框显示和隐藏
    const [value1, setValue1] = React.useState(['220000', '220300', '220303'])
    const [infoAddr, setInfoAddr] = useState('')
    const [addrAll, setAddrAll] = useState('')//详细个人信息（姓名+电话+地址）
    const [areaFlag, setAreaFlag] = useState(true)

    const [list, setList] = useState([])   //选择回收数据
    const [flag1, setFlag1] = useState(true)
    const [idx, setIdx] = useState('')
    useEffect(() => { getlist() }, [])
    const getlist = async () => {
        const { data } = await axios.get('/lmy/list')
        // console.log(data);
        setList(data.list)
    }
    const editStatus = async (id, status) => {
        const { data } = await axios.put('/lmy/editStatus', {
            _id: id,
            status: !status
        })
        console.log(data);
        if (data.code == 200) {
            message.success('添加成功')
            getlist()
            setFlag1(false)
        }
    }
    const newlist = useMemo(() => {
        if (list.filter(item => item.status == true).length > 0) {
            return list.filter(item => item.status == true)
        } else {
            return []
        }
    }, [list.filter(item => item.status == true)])
    const recovery = () => {
        navigate('/myorder', { state: { list: newlist } })
        setFlag1(true)
    }

    // 模态框显示
    const showModal = () => {
        setIsModalOpen(true);
    };
    // 请求后端添加地址接口
    const handleOk = async () => {
        // 将编码转换为对应的地址
        const selectedAreaNames = value1.map(code => {
            const province = areaList.province_list[code.substring(0, 2) + '0000'] || ''
            const city = areaList.city_list[code.substring(0, 4) + '00'] || ''
            const county = areaList.county_list[code] || ''
            const address = province + city + county
            return address
        });
        const address = selectedAreaNames[2] + form.getFieldValue('addrDetail1');
        const address1 = infoAddr + form.getFieldValue('addrDetail1');
        const { data } = await axios.post('http://localhost:3000/lmy/addaddr', {
            addr_name: form.getFieldValue('addrName1'),
            phone: form.getFieldValue('addrPhone1'),
            addr: areaFlag ? address : address1
        })
        // console.log(data);
        if (data.code == 200) {
            message.success('添加地址成功')
            setIsModalOpen(false)
            form.setFieldValue('addrName1', '')
            form.setFieldValue('addrPhone1', '')
            form.setFieldValue('addrDetail1', '')
            form.setFieldValue('area', '')
            setAddrAll('')
        } else {
            message.error('添加地址失败')
        }
    };
    // 关闭模态框
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 粘贴
    const handlePaste = async (e) => {
        const pastedText = e.clipboardData.getData('text/plain');
        // 在这里对粘贴的文本进行地址识别和处理
        const processedAddress = await processAddress(pastedText);
        // 更新地址字段的值
        setAddrAll(processedAddress);

        // 阻止默认粘贴行为
        e.preventDefault();
    }
    //   对粘贴的文本进行地址识别和处理
    const processAddress = (address1) => {
        // 可以使用正则表达式、关键词匹配等方法进行地址识别和处理
        const regex = /(.*省|.*自治区)?(.*市|.*自治州|.*地区)?(.+)/;
        const match = address1.match(regex);
        // console.log(match);
        if (match) {
            const province1 = match[1] || '';
            const city1 = match[2] || '';
            const street = match[3] || '';
            // console.log(province1, city1, street);
            // 去除多余的空格
            // province1=province1.trim();
            // city1=city1.trim();
            // street=street.trim();

            // 统一格式
            // province1=province1.replace('省', '');
            // city1=city1.replace('市', '');

            // 返回处理后的地址
            return `${province1}${city1}${street}`;
        }
        return address1;
    }
    // 识别地址，进行填充
    const identify = async () => {
        const addr1 = await processAddress(addrAll);
        // 使用正则表达式匹配不同部分
        const nameRegex = /^([\u4e00-\u9fa5]+)/; // 匹配中文姓名
        const phoneRegex = /(\d{11})/; // 匹配手机号
        const addressRegex = /([\u4e00-\u9fa5]+)/g;  // 匹配中文省市区和详细地址
        // console.log(nameRegex, phoneRegex, addressRegex);
        const nameMatch = addr1.match(nameRegex);     //姓名
        const phoneMatch = addr1.match(phoneRegex);    //手机号
        const addressMatches = addr1.match(addressRegex);   //地址
        // console.log(nameMatch.input.split(' '), phoneMatch, addressMatches);
        // 提取匹配到的部分
        const name1 = nameMatch[0];
        const phoneNumber1 = phoneMatch[0];
        const province2 = addressMatches[1].split(/省|市|区|县/)
        // 更新状态
        form.setFieldValue('addrName1', name1)
        form.setFieldValue('addrPhone1', phoneNumber1)
        form.setFieldValue('addrDetail1', nameMatch.input.split(' ')[2])
        setInfoAddr(province2[0] + '省' + province2[1] + '市' + province2[2] + '区')
        setAreaFlag(false)
    }


    return (
        <div>
            <div className="head">
                <NavBar
                    title="上门回收"
                    leftText=""
                    rightText={<MoreOutlined style={{ fontSize: '20px' }} />}
                    onClickLeft={() => { navigate(-1) }}
                    onClickRight={() => Toast('按钮')}
                />
            </div>
            <div className="main">
                <Card className='card'>
                    {
                        flag1 ? <div>
                            <p style={{
                                marginBottom: '20px',
                                marginTop: '20px',
                                fontSize: '18px',
                            }}>请添加你需要回收的物品吧</p>
                            <p onClick={() => { setVisible1(true) }}>
                                <span className='add'>+</span>
                                <span className='add1' >立即添加</span>
                            </p>
                        </div> : <div style={{
                            width:'100%',
                            height:'200px',
                            overflow:'hidden',
                            overflowY:'scroll',
                        }}>
                            {
                                list.filter(item => item.status == true).map(item1 => {
                                    return <div key={item1._id}  >
                                        <img src={item1.img} alt="" style={{ width: '100px', height: '150px' }} />
                                        <h4>{item1.title}</h4>
                                        <p>{item1.num}元</p>
                                    </div>
                                })
                            }
                        </div>
                    }


                </Card>
                <Card className='card1'>
                    <p style={{ width: '100%' }}>你的地址<span className='address' onClick={showModal}>填写所在地址<RightOutlined /></span></p><br />
                    <Modal title="填写所在地址"
                        style={{
                            top: '200px'
                        }}
                        open={isModalOpen}
                        onOk={handleOk}
                        onCancel={handleCancel}
                    >
                        <Input.TextArea
                            placeholder="请填入地址信息"
                            value={addrAll}
                            maxLength={100}
                            showCount
                            onChange={(event) => setAddrAll(event.target.value)}
                            onPaste={handlePaste} />
                        <br />
                        <p style={{
                            width: '50px',
                            float: 'right',
                            marginTop: '20px',
                            textAlign: 'center',
                            color: 'red'
                        }} onClick={() => {
                            identify()
                        }}>识别</p>

                        <Form
                            form={form}
                            name="basic"
                            labelCol={{
                                span: 8,
                            }}
                            wrapperCol={{
                                span: 16,
                            }}
                            style={{
                                maxWidth: 600,
                                marginTop: '50px'
                            }}
                            initialValues={{
                                remember: true,
                            }}
                            // onFinish={onFinish}
                            // onFinishFailed={onFinishFailed}
                            autoComplete="off"
                        >
                            <Form.Item
                                label="收货人"
                                name="addrName1"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入收货人姓名',
                                    },
                                ]}
                            >
                                <Input placeholder='收货人姓名' />
                            </Form.Item>

                            <Form.Item
                                label="手机号"
                                name="addrPhone1"
                                rules={[
                                    {
                                        required: true,
                                        pattern: /^1[3-9]\d{9}$/,
                                        message: '请输入收货人手机号',
                                    },
                                ]}
                            >
                                <Input placeholder='收货人手机号' />
                            </Form.Item>

                            <Form.Item
                                name="area"
                            >
                                <div>
                                    {
                                        areaFlag ? <Area
                                            popup={{
                                                round: true,
                                            }}
                                            title='地址'
                                            value={value1}
                                            areaList={areaList}
                                            onConfirm={setValue1}
                                        >
                                            {(_, selectRows, actions) => {
                                                return (
                                                    <Field
                                                        label='选择地区'
                                                        value={selectRows.map(row => row?.text).join(',')}
                                                        onClick={() => actions.open()}
                                                    />
                                                )
                                            }}
                                        </Area> : <div>
                                            <label>地区</label><input type="text"
                                                style={{ border: '1px solid #eee', marginLeft: '10px' }}
                                                value={infoAddr} onChange={(e) => { setInfoAddr(e.target.value) }} />
                                        </div>
                                    }
                                </div>


                            </Form.Item>
                            <Form.Item
                                label='详细地址'
                                name="addrDetail1"

                            >
                                {/* <div style={{
                                    position: 'relative'
                                }}> */}
                                <Input placeholder='如街道、门牌号、小区、乡镇、村等'
                                />
                                {/* <img src="/lmyimage/定位.png" alt="" style={{
                                        width: '20px',
                                        height: '20px',
                                        position: 'absolute',
                                        right: '10px',
                                        top: "5px"
                                    }} /> */}
                                {/* </div> */}

                            </Form.Item>
                        </Form>
                    </Modal>
                    <p>回收时间 <span className='address'>选择预约时间<RightOutlined /></span></p><br />
                    <p>物品属性<span className='address'>描述物品状态<RightOutlined /></span></p><br />
                    <p>上传图片<span className='address'>将要回收的物品拍照<RightOutlined /></span></p>
                </Card>
                <Card className='card2'>
                    <p>服务费<span style={{ border: '1px solid green', float: 'right', color: 'green', borderRadius: '5px', padding: '2px 5px' }}>首单减免</span></p>
                </Card>
                <div className="footer">
                    <Button color='success' onClick={() => { recovery() }}>立即回收</Button>
                </div>
            </div>·
            <Popup
                visible={visible1}
                showCloseButton
                onMaskClick={() => {
                    setVisible1(false)
                }}
                onClose={() => {
                    setVisible1(false)
                }}
                bodyStyle={{ height: '60vh', overflowY: 'scroll' }}
            >
                <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
                    {
                        list.filter(ele => ele.status == false).map(item => {
                            return <div key={item._id} style={{
                                border: idx == item._id ? '1px solid red' : '1px solid #ccc',
                                width: '200px',
                                textAlign: 'center',
                                marginTop: '10px'
                            }} onClick={() => {
                                setIdx(item._id)
                                editStatus(item._id, item.status)
                            }}>
                                <img src={item.img} alt="" style={{ width: '150px', height: '200px' }} />
                                <h4>{item.title}</h4>
                                <p>{item.num}元</p>
                            </div>
                        })
                    }
                </div>

            </Popup>
        </div>
    )
}
